/* components */
import FieldComponents from '@src/component/AdvancedSearch/FieldComponents'
import ConnectorModuleRuleFormItemApp from '@src/modules/connector/components/rule-form/item-form-app'
/* model */
import { 
  ConnectorConditionSelectList,
  ConnectorConditionDateSelectList,
  ConnectorConditionInsertList,
  ConnectorConditionLocationList, 
  ConnectorConditionTypeEnum, 
  ConnectorFromField, 
  ConnectorModuleComponentNameEnum, 
  ConnectorOptionsOperate, 
  ConnectorToField,
  ConnectorFieldOperateEnum, 
  ConnectorFieldNameEnum,
  ConnectorConditionTagsSelectList,
  ConnectorBizTypeEnum,
  ConnectorFieldEnNameEnum,
  ConnectorConditionFromFieldSelectList,
  ConnectorBizTypeIdEnum,
  ConnectorFieldTypeEnum,
  ActionCreateParams,
} from '@src/modules/connector/model'
/* enum */
import type Field from '@src/model/Field'
/* scss */
import '@src/modules/connector/components/rule-form/item.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, PropType, ref } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement } from 'vue'
/* types */
import { ConnectorRuleFormItemType } from '@src/modules/connector/types'
/* utils */
import { isFalsy } from '@src/util/type'
import { 
  connectorToField2FormField,
  createConnectorRuleFormItem,
  isConnectorFixedValueMultiField,
  isConnectorRuleFormConditionAppFromField,
  isConnectorRuleFormConditionEmpty, 
  isConnectorRuleFormConditionFixedValue, 
  isConnectorRuleFormConditionFromField,
  matchFieldToTransform
} from '@src/modules/connector/util'
/* advanced util */
import { genComponent } from '@src/component/AdvancedSearch/advancedSearch'
import { initialize } from '@src/component/form/util'
import { t } from '@src/locales'
import _, { cloneDeep, isArray, isString, isNumber } from 'lodash'
import { uuid } from '@src/util/lang/string'

export type ConnectorModuleRuleFormItemProps = {
  fromFieldList: ConnectorFromField[];
  isShowOperate: boolean;
  isFirst: boolean;
  isSelect: boolean;
  toFieldList: ConnectorToField[];
  toFieldListMap: Record<string, ConnectorToField>;
  value: ConnectorRuleFormItemType;
  existFieldList: ConnectorRuleFormItemType[];
  justFixedValue: boolean;
  requiredShowDel:boolean;
  showText:boolean;
  isUpdate:boolean;
  toBizTypeId: string;
}

export interface ConnectorModuleRuleFormItemSetupState {
  
}

export enum ConnectorModuleRuleFormItemEmitEventNameEnum {
  Input = 'input',
  Delete = 'delete',
}

export type ConnectorModuleRuleFormItemInstance = ComponentInstance & ConnectorModuleRuleFormItemSetupState
export type ConnectorModuleRuleFormItemVM = ComponentRenderProxy<ConnectorModuleRuleFormItemProps> & CommonComponentInstance & ConnectorModuleRuleFormItemInstance

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorModuleRuleFormItem,
  inject: ['isTrigger'],
  components: {
    ...FieldComponents
  },
  emits: [
    ConnectorModuleRuleFormItemEmitEventNameEnum.Input,
    ConnectorModuleRuleFormItemEmitEventNameEnum.Delete,
  ],
  props: {
    fromBizTypeName: {
      type: String as PropType<string>,
      default: ''
    },
    fromFieldList: {
      type: Array as PropType<ConnectorFromField[]>,
      default: () => ([])
    },
    isFirst: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    isShowOperate: {
      type: Boolean as PropType<boolean>,
      default: true
    },
    isSelect: {
      type: Boolean as PropType<boolean>,
      default: true
    },
    toFieldList: {
      type: Array as PropType<ConnectorToField[]>,
      default: () => ([])
    },
    existFieldList: {
      type: Array as PropType<ConnectorRuleFormItemType[]>,
      default: () => ([])
    },
    toFieldListMap: {
      type: Object as PropType<Record<string, ConnectorToField>>,
      default: () => ({})
    },
    value: {
      type: Object as PropType<ConnectorRuleFormItemType>,
      default: () => ({}),
    },
    justFixedValue: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    requiredShowDel:{
      type: Boolean as PropType<boolean>,
      default: true
    },
    showText:{
      type: Boolean as PropType<boolean>,
      default: false
    },
    isUpdate:{
      type: Boolean as PropType<boolean>,
      default: false
    },
    validation: {
      type: Boolean,
      default: false
    },
    toBizTypeId: {
      type: String as PropType<string>,
      default: ''
    },
    isWiki: {
      type: Boolean,
      default: false
    },
    nodeConfig: {
      type: Object,
      default: () => ({}),
    },
    isMultipleChoose: {
      type: Boolean,
      default: false
    }
  },
  setup(props: ConnectorModuleRuleFormItemProps, { emit }) {
    let rightFieldSelectKey = ref(0)

    const connectorModuleRuleFormItemAppKey = ref(uuid())

    return {
      rightFieldSelectKey,
      connectorModuleRuleFormItemAppKey
    }
  },
  computed: {
    /**
     * @description 当前选择的 to 字段
    */
    currentToField(): ConnectorToField | undefined {
      if (!this.isMultipleChoose) return this.toFieldListMap[this.value.leftFieldValue]
      const parent = this.value.leftFieldValue.split('.').shift()
      const current = this.value.leftFieldValue.split('.').pop()
      if (parent === current) {
        return this.toFieldListMap[parent]
      } else {
        return this.toFieldListMap[parent]?.children.find((item: ConnectorToField) => item.enName === current);
      }
    },
    /**
     * @description 当前选择的 to 字段 父字段fieldName
    */
    parentFieldName(): string {
      return this.currentToField?.parentEnName || ''
    },
    /**
     * @description 当前选择的 to 字段 父字段值
    */
    parentValue(): ConnectorRuleFormItemType | undefined {
      return this.existFieldList.find(v => v.leftFieldValue == this.parentFieldName)
    },
    /**
     * @description 当前选择的 to 字段 是否为空
    */
    isCurrentToFieldEmpty(): boolean {
      return isFalsy(this.currentToField)
    },
    /**
     * @description 是否禁用除了 to 字段 以外的所有的 select 选择
    */
    isDisabledExceptToFieldSelect(): boolean {
      return this.isCurrentToFieldEmpty
    },
    /**
     * @description 是否禁用 from 字段  select 选择
    */
    isDisabledFromFieldSelect(): boolean {
      return this.isDisabledExceptToFieldSelect || this.isJsonObject
    },
    /** 
     * @description 当前字段 对应的条件 是否为 置空
    */
    isConditionEmpty(): boolean {
      return this.value.condition == ConnectorConditionTypeEnum.Empty
    },
    /** 
     * @description 是否需要显示 必填内容
    */
    isShowRequiredContent(): boolean {
      return Boolean(!this.isSelect && this.currentToField?.required)
    },
    isJsonArray(): boolean {
      return this.currentToField?.fieldType === ConnectorFieldTypeEnum.JsonArray
    },
    isJsonObject(): boolean {
      return this.currentToField?.fieldType === ConnectorFieldTypeEnum.JsonObject
    },
    /** 
     * @description 左侧显示的字段列表
    */
    leftFieldList(): ConnectorToField[] {
      // 这里要clone出来要不外面toFieldList改动会导致这样死循环
      const toFieldList = cloneDeep(this.toFieldList).filter(item => {
        const { parentEnName = '' } = item
        return parentEnName == this.parentFieldName
      })

      let fieldList = toFieldList.filter(item => {
        
        
        if (item.enName == this.value.leftFieldValue) {
          
          return true
        }
        
        // 可重复选择
        if(this.nodeConfig?.type == 2) {
          return true;
        }
        
        return this.existFieldList.every(exist => exist.leftFieldValue != item.enName)
      })
      
      if (this.isSelect) {
        // 查询 需要过滤显示 supportSelect 为 true
        fieldList = fieldList.filter(item => item.supportSelect)
      } else if(this.isUpdate) {
        // 编辑 需要过滤显示 supportUpdate和supportInsert 均为 true
        fieldList = fieldList.filter(item => item.supportUpdate && item.supportInsert)
      } else {
        // 新增 需要过滤显示 supportInsert 为 true
        fieldList = fieldList.filter(item => item.supportInsert)
      }
      
      return fieldList.map((item:any)=>{
        if(!item.children || item.children.length < 1){
          delete item.children
        }else {
          (item.children || []).forEach((child:any)=>{
            child.enName = `${item.enName}.${child.enName}`
            delete child.children
          })
        }

        return item
      })
    },
    /** 
     * @description 右侧显示的字段列表
    */
    rightFieldList(): ConnectorFromField[] {
      let fromFieldList = _.cloneDeep(this.fromFieldList)

      const sameFormFieldList = fromFieldList.map((item: any) => {
        if (!item.children || item.children.length < 1) {
          delete item.children
        } else {
          (item.children || []).forEach((child: any) => {
            // TODO 后续会出现不兼容数据
            let lastEnName = child.enName.split('.').pop()
            let lastItemEnName = item.enName.split('.').pop()
            child.enName = `${lastItemEnName}.${lastEnName}`
            delete child.children
          })
        }

        return item
      })

      fromFieldList = this.filterTypeTree(sameFormFieldList)
        .filter((item: any) => {
          if (item.enName == ConnectorFieldNameEnum.Tags) return false

          if (!matchFieldToTransform(this.currentToField, item) && (!item.children || (item.children || []).findIndex((child: any) => { return !child.disabled }) === -1)) {
            return false
          }
          
          if(!this.isJsonArray && item.fieldType === ConnectorFieldTypeEnum.JsonArray && !this.parentFieldName) return false;

          return true
        })
        
      // 判断是否子字段
      if (!this.parentFieldName) return fromFieldList

      // 父字段类型
      const parentType = this.toFieldListMap[this.parentFieldName]?.fieldType

      // 父字段是jsonArray 
      if (parentType === ConnectorFieldTypeEnum.JsonArray) {

        // 未选择 右侧字段 其子字段不可以选择
        if (!this.parentValue?.rightFieldValue) return []

        // 子字段只能选择父字段 from 对应的jsonArray下的子字段和其他类型字段（即不可以选择别的jsonArray）
        return fromFieldList.filter(field => field.fieldType !== parentType || field.fieldType === parentType && field.enName === this.parentValue?.rightFieldValue)
      }

      // 父字段是jsonObject
      if (parentType === ConnectorFieldTypeEnum.JsonObject) {

        // 子字段不能选择jsonArray
        return fromFieldList.filter(field => field.fieldType !== ConnectorFieldTypeEnum.JsonArray)
      }

      return fromFieldList
    },
    /**
     * @description 当前选择的 to 字段 的 操作符列表
     */
    operateList(): ConnectorOptionsOperate[] {
      return this.currentToField?.operateList || []
    },
    // 取值方式
    connectorConditionSelectList(){
      const connectorConditionInsertList = !this.isTrigger || this.parentFieldName ? ConnectorConditionInsertList.slice(0, 2) : ConnectorConditionInsertList
      
      // 知识库取值方式为固定值
      if(this.justFixedValue || this.isWiki){
        // 如果是知识库的分类字段需要有对应字段
        if(this.currentToField?.enName === 'typeId_cascader') {
          return connectorConditionInsertList
        }
        // 固定值
        return ConnectorConditionTagsSelectList
      }
      
      // to 表单不为客户类型时
      if (this.toBizTypeId && this.toBizTypeId !== ConnectorBizTypeIdEnum.Customer) {
        
        // 联系人 和 客户地址 字段只能选择 对应字段
        if (
          this.currentToField?.enName == ConnectorFieldEnNameEnum.Linkman
          || this.currentToField?.enName == ConnectorFieldEnNameEnum.CustomerAddress
        ) {
          return ConnectorConditionFromFieldSelectList
        }
        
      }
      
      // @ts-ignore
      const isLocationType = this.currentToField?.fieldType === 'customerAddress' || this.currentToField?.fieldType === 'location' || this.currentToField?.fieldType === 'autograph'
      
      // 服务部门字段暂时不支持对应字段
      if (this.currentToField?.enName == ConnectorFieldNameEnum.Tags) {
        return ConnectorConditionTagsSelectList
      }
      
      if(this.isSelect) {
        // 日期类型 操作符是介于没有对应字段选项
        if(this.value?.componentName === 'date-search' && this.value?.operator === ConnectorFieldOperateEnum.Between) {
          return ConnectorConditionDateSelectList
        }
        // 客户地址和位置没有固定值选择
        if(isLocationType) {
          return ConnectorConditionLocationList
        }
        return !this.isTrigger ? ConnectorConditionSelectList.slice(0, 3) : ConnectorConditionSelectList
      }

      if (this.isJsonArray || this.isJsonObject) {
        return ConnectorConditionFromFieldSelectList
      }

      // 插入取值方式没有置空选项
      return isLocationType ? [{ value: ConnectorConditionTypeEnum.FromField, label: t('common.connector.fixedValue') }] : connectorConditionInsertList
    },
    isRichText() {
      return this.isWiki && this.currentToField?.fieldType == 'rich_text'
    },
    // 是否时间选择类型
    isDateField() {
      return ['date', 'datetime'].includes(this.currentToField?.fieldType)
    },
  },
  watch: {
    rightFieldList: {
      handler(newValue) {
        /** 
         * @description el-cascader options更新后 newValue没有之前选中的值就会报错
         * 给el-cascader设置一个key，当options变更时也改变key值，el-cascader就会重新渲染
        */
        this.rightFieldSelectKey ++
      }
    }
  },
  mounted() {
    this.initiate()
  },
  methods: {
    /**
     * @description 改变 来自于字段 固定值 对应的 组件
    */
    changeFromFieldSelectComponent(value: string) {
      let currentToField;
      if (!this.isMultipleChoose) {
        currentToField = this.toFieldListMap[value]
      } else {
        const parent = this.value.leftFieldValue.split('.').shift()
        const current = this.value.leftFieldValue.split('.').pop()
        if (parent === current) {
          currentToField = this.toFieldListMap[parent]
        } else {
          currentToField = this.toFieldListMap[parent]?.children.find((item: ConnectorToField) => item.enName === current);
        }
      }
      
      if(!currentToField) return
      
      // TODO: 临时这么写
      const field = {
        ...currentToField,
        formType: currentToField?.fieldType,
        fieldName: currentToField?.enName,
      } as unknown as Field
      
      const options = {
        field,
        operator: this.value.operator,
        isInsert: !this.isSelect,
        isConnector: true
      }
      
      // TODO: 修改
      const { component, bind } = genComponent(options)
      this.value.componentName = component
      this.value.bind = bind
      
      // TODO: 修改
      const formValue = initialize([field])
      
      const fieldValue = formValue[Object.keys(formValue)[0]]
      
      this.value.value = fieldValue
      
    },
    initiate() {
      const value = cloneDeep(this.value.value)
      this.$nextTick(() => {
        this.value.field = connectorToField2FormField(this.currentToField)
        this.onConditionSelectChangeHandler(this.value.condition)
        this.value.value = value
      })
    },
    /** 
     * @description 初始化 操作符 值
    */
    initOperateValue() {
      
      // 默认取操作符列表第一个
      const firstOperateValue = this.operateList?.[0]?.enName
      const hasOperator = (this.operateList || []).filter(item=>{return item.enName == this.value.operator}).length > 0
      if(this.currentToField){
        this.value.operator = hasOperator ? _.cloneDeep(this.value.operator) : firstOperateValue
      }
      // this.value.operator = firstOperateValue
      
    },
    /** 
     * @description 去往的 字段列表选择 变化事件
    */
    onLeftToFieldSelectChangeHandler(value: string) {
      if (this.isMultipleChoose) this.$refs.cascaderHandle.dropDownVisible = false;
      this.onOldLeftToFieldSelectChangeHandler(this.value.leftFieldValue)
      
      this.value.leftFieldValue = value
      // 清空右边值
      this.value.rightFieldValue = ''
      this.initOperateValue()
      
      this.changeFromFieldSelectComponent(value)
      
      this.$nextTick(() => {
        this.value.field = connectorToField2FormField(this.currentToField)
        const { field, operator } = this.value
        // 查询的时候 如果字段类型是date 操作符是between取值方式就没有对应字段了
        if(this.isSelect && (field?.formType === 'date' || field?.formType === 'datetime') && operator === ConnectorFieldOperateEnum.Between) {
          this.value.condition = ConnectorConditionTypeEnum.FixedValue
          return
        }
        this.value.condition = this.connectorConditionSelectList[0].value

        this.value.required = this.currentToField?.required

        this.onNewLeftToFieldSelectChangeHandler(value)
      })
      
    },
    /** 
     * @description 去往的 字段列表选择 旧值 (子表单)
    */
    onOldLeftToFieldSelectChangeHandler(oldValue: string) {
      
      if (oldValue) {
        // 原来字段是子表单时 需删除子字段
        const isExist = this.existFieldList.some(f => f.parentEnName == oldValue)
  
        if (isExist) {
          const value = this.existFieldList.filter(f => f.parentEnName != oldValue)
  
          this.onRuleFormValueInputHandler(value)
        }
      }

    },
    /** 
     * @description 去往的 字段列表选择 新值 (子表单)
    */
    onNewLeftToFieldSelectChangeHandler(newValue: string) {

      if (newValue) {
        // 新字段是子表单时 需新增子字段
        const isExist = this.toFieldList.some(f => f.parentEnName == newValue)
  
        if (isExist) {
          const insertRuleFormItems = this.toFieldList
            .filter(f => f.parentEnName == newValue)
            .map(toField => {
              return createConnectorRuleFormItem(toField)
            })
          
          // 合并
          const ruleFormItems = [this.value, ...insertRuleFormItems]
          
          // 坐标
          const index = this.existFieldList.findIndex(f => f.leftFieldValue == newValue)
          
          // 拷贝数据 不影响改动
          let result = _.cloneDeep(this.existFieldList)

          // 向指定坐标插入合并的字段
          result.splice(index, 1, ...ruleFormItems)

          this.onRuleFormValueInputHandler(result)
        }
      }

    },
    /** 
     * @description 取值方式 变化事件
    */
    onConditionSelectChangeHandler(value: ConnectorConditionTypeEnum) {
      
      this.value.condition = value
      
      this.initOperateValue()
      
      this.changeFromFieldSelectComponent(this.value.leftFieldValue)
      
    },
    /** 
     * @description 右侧 来自于的 对应字段 对应的选择 变化事件
    */
    onRightFromFieldFromFieldSelectChangeHandler(value: string) {
      if (this.isJsonArray) {

        const fieldValues = this.existFieldList.map(field => {
          // 重置子字段 右侧 from 值
          if (field.parentEnName === this.currentToField?.enName) {
            field.rightFieldValue = ''
          }

          return field
        })
          
        this.onRuleFormValueInputHandler(fieldValues)
      }
      
      this.value.rightFieldValue = value
      
      this.changeFromFieldSelectComponent(this.value.leftFieldValue)
      
    },

    handleAppFromFieldChange(v: ActionCreateParams) {
      const value = cloneDeep(v)
      Reflect.deleteProperty(value, 'toRequestFieldList')
      Reflect.deleteProperty(value, 'toResponseFieldList')
      this.value.value = JSON.stringify(value)

      this.connectorModuleRuleFormItemAppKey = uuid()
    },
    /** 
     * @description 操作符 变化事件
    */
    onOperateSelectChangeHandler(value: ConnectorFieldOperateEnum) {
      this.value.operator = value
      if (this.isDateField){
        this.value.value = ''
      }
    },
    /** 
     * @description 删除当前项事件
    */
    onDeleteRuleFormItemHandler() {
      // 删除父字段 需同时删掉子字段
      this.onOldLeftToFieldSelectChangeHandler(this.value.leftFieldValue)

      this.$nextTick(() => {
        this.$emit(ConnectorModuleRuleFormItemEmitEventNameEnum.Delete, this.value)
      })
    },
    /**
     * @description 数据变化事件
    */
    onRuleFormValueInputHandler(value: ConnectorRuleFormItemType[]) {
      this.$emit(ConnectorModuleRuleFormItemEmitEventNameEnum.Input, value)
    },
    /** 
     * @description 渲染左侧 去往的 字段列表选择 只显示supportSelect为true的
    */
    renderLeftToFieldSelect(h: CreateElement) {
      const attrs = {
        props:{
          props: {
            checkStrictly: this.isMultipleChoose,
            label:'cnName',
            value:'enName',
            emitPath:false
          }
        }
      }
      return (
        // <el-select
        //   filterable
        //   class="connector-module-rule-form-item-left-to-field-select"
        //   placeholder="请选择关联应用字段"
        //   value={this.value.leftFieldValue}
        //   onChange={this.onLeftToFieldSelectChangeHandler}
        // >
        //   {this.leftFieldList.map(toField => {
        //     return (
        //       <el-option
        //         key={toField.enName}
        //         label={toField.cnName}
        //         value={toField.enName}
        //       />
        //     )
        //   })}
        // </el-select>
        <el-cascader
          class={['connector-module-rule-form-item-left-to-field-select', this.parentFieldName && 'indent']}
          options={this.leftFieldList}
          value={this.value.leftFieldValue}
          onChange={this.onLeftToFieldSelectChangeHandler}
          expandTrigger={this.isMultipleChoose? 'hover' : 'click'}
          placeholder={t('common.connector.tips.tip10')}
          filterable
          ref="cascaderHandle"
          {...attrs}
        >
        </el-cascader>
      )
    },
    /** 
     * @description 渲染 操作符 选择
    */
    renderOperateSelect(h: CreateElement) {
      return (
        <el-select
          class="connector-module-rule-form-item-operate-select"
          placeholder={t('common.connector.discriminator')}
          disabled={this.isDisabledExceptToFieldSelect}
          value={this.value.operator}
          onChange={this.onOperateSelectChangeHandler}
        >
          {this.operateList.map(operator => {
            return (
              <el-option
                key={operator.enName}
                label={operator.cnName}
                value={operator.enName}
              />
            )
          })}
        </el-select>
      )
    },
    /** 
     * @description 渲染 条件 选择
    */
    renderConditionSelect(h: CreateElement) {
      return (
        <el-select
          class="connector-module-rule-form-item-condition-select"
          placeholder={t('common.placeholder.selectSomething', {0: t('common.connector.takeValueMethod')})}
          disabled={this.isDisabledExceptToFieldSelect}
          value={this.value.condition}
          onChange={this.onConditionSelectChangeHandler}
        >
          {this.connectorConditionSelectList.map(item => {
            return (
              <el-option
                key={item.value}
                label={item.label}
                value={item.value}
              />
            )
          })}
        </el-select>
      )
    },
    /** 
     * @description 渲染右侧 来自于的 字段列表选择
    */
    renderRightFromFieldSelect(h: CreateElement) {
      
      const isEmpty = isConnectorRuleFormConditionEmpty(this.value.condition)
      
      // 当前字段 对应的条件 是否为 置空 则 不渲染
      // 现在增加不为空和为空保持一致
      if (isEmpty || this.value.operator == 'EMPTY' || this.value.operator == 'NOT_EMPTY') {
        // return null
        return this.renderEmpty(h)
      }
      
      // 当前字段 对应的条件 是否为 固定值 则 渲染 对应组件
      const isFixedValue = isConnectorRuleFormConditionFixedValue(this.value.condition)
      if (isFixedValue) {
        return this.renderRightFromFieldFixedValueSelect(h)
      }
      
      // 当前字段 对应的条件 是否为 对应字段 则 渲染 对应组件
      const isFromField = isConnectorRuleFormConditionFromField(this.value.condition)
      if (isFromField) {
        return this.renderRightFromFieldFormFieldSelect(h)
      }
      // 当前字段 对应的条件 是否 第三方应用表单

      const isAppFromField = isConnectorRuleFormConditionAppFromField(this.value.condition)
      if (isAppFromField) {
        return this.renderAppFromField(h)
      }
      
      return null
    },
    /** 
     * @description 渲染右侧 来自于的 固定值 对应的选择组件
    */
    renderRightFromFieldFixedValueSelect(h: CreateElement) {

      // 数字类型操作符转换
      if(this.currentToField?.fieldType == 'number'){
        if(this.value.operator == 'BETWEEN' || this.value.operator == 'NOT_BETWEEN'){
          this.value.componentName = 'number-range'
        } else {
          if(isArray(this.value.value)){
            this.value.value = ''
          }
          this.value.componentName = 'number-search'
        }
      }

      //日期类型操作符转换
      // if(this.currentToField?.fieldType == 'date'){
      //   if(this.value.operator == 'EARLY' || this.value.operator == 'LATELY'){
      //     this.value.bind.type = 'date'
      //     this.value.bind.isRange = false
      //     if(isArray(this.value.value)){
      //       this.value.value = ''
      //     }
      //   } else {
      //     this.value.bind.type = 'daterange'
      //     this.value.bind.isRange = true
      //   }
      // }

      const multiple = isConnectorFixedValueMultiField(this.currentToField)

      // 修复计划开始时间和计划结束时间下拉控件不显示的问题
      let timeType = [
        'planStartTime',
        'planEndTime',
      ]
      
      let isRange = this.isSelect
      let { operator = '', value = '', field = {}  } = this.value
      // 兼容时间选择类型
      if (this.isDateField) {
        // 把非BETWEEN(介于)的时间选择控件转换成 daterange
        isRange = operator === 'BETWEEN' && !this.isRichText && this.isShowOperate
        // 把 EARLY（早于），LATE（晚于）的值改成number（回显用，存的时候是个数组）
        if (this.isNeedCompatibleDataTimeOperate(operator) && isArray(value)) {
          value = value?.[0] ?? ''
        }
      }
      const component = (
        h(
          this.value.componentName, 
          {
            props: {
              ...this.value.bind,
              value,
              field: {
                ...this.currentToField,
                formType: this.currentToField?.fieldType || '',
                fieldName: this.currentToField?.enName || '',
                displayName: this.currentToField?.cnName || '',
              },
              //@ts-ignore
              type: timeType.includes(this.currentToField?.fieldType) ? 'datetime'  : this.currentToField?.fieldType ,
              isRange,
              isConnector: true,
              multiple: this.currentToField?.fieldType === 'user' ? this.currentToField?.setting?.isMultiple || false : multiple
            },
            on: {
              update: (value: any) => {
                this.value.value = value
              },
              input: (value: any) => {
                this.value.value = value
              }
            }
          }
        )
      )
      
      return (
        <form-item validation={this.validation} class={this.isRichText ? 'form-item-trigger-rich_text' : ''}>
          { component }
        </form-item>
      )
    },
    /** 
     * @description 渲染右侧 来自于的 对应字段 对应的选择
    */
    renderRightFromFieldFormFieldSelect(h: CreateElement) {
      const attrs = {
        props:{
          props: {
            checkStrictly: false,
            label:'cnName',
            value:'enName',
            emitPath:false
          },
          'popper-class': 'connector-module-rule-form-item-right-from-field-form-field-select__popper'
        }
      }

      let classNames = 'connector-module-rule-form-item-right-from-field-form-field-select'
      if(this.isTrigger) {
        classNames = `${classNames} connector-module-rule-form-item-right-from-field-form-field-select-trigger`
      }

      return (
        <el-cascader
          class={classNames}
          ref="rightFromFieldFormFieldSelectRef"
          options={this.rightFieldList}
          disabled={this.isDisabledFromFieldSelect}
          placeholder={t('common.connector.tips.tip11')}
          key={this.rightFieldSelectKey}
          value={this.value.rightFieldValue}
          onChange={this.onRightFromFieldFromFieldSelectChangeHandler}
          filterable
          {...attrs}>
        </el-cascader>
      )
    },

    renderAppFromField(h: CreateElement) {
      return (
        <ConnectorModuleRuleFormItemApp
          key={this.connectorModuleRuleFormItemAppKey} 
          currentToField={this.currentToField}
          parentFieldName={this.parentFieldName}
          parentValue={this.parentValue}
          isDisabledFromFieldSelect={this.isDisabledFromFieldSelect}
          fromFieldList={this.fromFieldList} 
          fromBizTypeName={this.fromBizTypeName}
          value={this.value.value}
          onChange={this.handleAppFromFieldChange}
        />
      )
    },
    renderEmpty(h: CreateElement) {
      return (
        <div style="width:160px" class="empty"></div>
      )
    },
    /** 
     * @description 渲染 删除按钮
    */
    renderDeleteButton(h: CreateElement) {
      return (
        <div class="connector-module-rule-form-item-delete-button">
          <span 
            class="connector-module-rule-form-item-delete-button-icon" 
            onClick={this.onDeleteRuleFormItemHandler}
          >
            <i class="iconfont icon-delete"></i>
          </span>
        </div>
      )
    },
    renderLeftConditionTip(h: CreateElement) {
      
      const text = this.isFirst ? t('common.connector.text.satisfy') : t('common.connector.text.and')
      
      return (
        <div class="connector-module-rule-form-item-left-condition-tip">
          <span class="connector-module-rule-form-item-left-condition-tip-text">
            { text }
          </span>
        </div>
      )
    },
    renderRequireContent(h: CreateElement) {
      return (
        <div class="connector-module-rule-form-item-required">
          *
        </div>
      )
    },
    filterTypeTree(fieldTree:ConnectorFromField[]){
      if(!this.currentToField) return []
      let matchFieldList = _.cloneDeep(fieldTree)
      matchFieldList.forEach((field:any)=>{
        // if(!matchFieldToTransform(this.currentToField,field)){
        //   field.disabled = true
        // }
        field.children && (field.children || []).forEach(
          (child:any) =>{
            // 数字、手机、邮箱匹配子字段需要完全匹配
            // if(this.currentToField?.fieldType && ['number','phone','email'].indexOf(this.currentToField?.fieldType)>-1 && child?.fieldType && child?.fieldType != this.currentToField?.fieldType){
            //   child.disabled = true
            // }
            if(!matchFieldToTransform(this.currentToField,child)){
              child.disabled = true
            }
          }
        )
        if(field.children && field.children.findIndex((child:any)=>{return !child.disabled}) === -1){
          delete field.children
        }
      })

      return matchFieldList
    },
    // 是否需要兼容时间类型的操作符
    isNeedCompatibleDataTimeOperate(operator: string) {
      return ['EARLY', 'LATE'].includes(operator)
    },
  },
  render(h: CreateElement) {
    return (
      <div class={ConnectorModuleComponentNameEnum.ConnectorModuleRuleFormItem}>
        
        {/* start 左侧的条件提示 */}
        { !this.isRichText && this.isSelect && (
          this.renderLeftConditionTip(h)
        )}
        {/* end 左侧的条件提示 */}
        
        { !this.isRichText && this.isUpdate && <div class='other-text'>{t('common.base.edit1')}</div>}

        {/* start 必填符号 */}
        { this.isShowRequiredContent && (
          this.renderRequireContent(h)
        )}
        {/* end 必填符号 */}
        
        {/* start 左侧 去往的 字段列表选择 */}
        { !this.isRichText && this.renderLeftToFieldSelect(h) }
        {/* end 左侧 去往的 字段列表选择 */}
        
        { !this.isRichText && this.showText && <div class='other-text'>{t('component.bizBatch.formLabel')}</div>}

        {/* start 操作符 选择 */}
        { !this.isRichText && this.isShowOperate && (
          this.renderOperateSelect(h)
        )}
        {/* end 操作符 选择 */}
        
        {/* start 条件 选择 */}
        { !this.isRichText && this.renderConditionSelect(h) }
        {/* end 条件 选择 */}
        
        {/* start 右侧 来自于的 字段列表选择 */}
        { this.renderRightFromFieldSelect(h) }
        {/* end 右侧 来自于的 字段列表选择 */}
        
        {/* start 删除按钮 富文本隐藏删除按钮*/}
        { (this.isShowRequiredContent && !this.requiredShowDel) || this.isRichText || this.parentFieldName ? '' : this.renderDeleteButton(h) }
        {/* end 删除按钮 */}
        
      </div>
    )
  }
})
